require('dotenv').config();

const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'password',
  database: process.env.DB_NAME || 'xiqu_db',
  waitForConnections: true,
  connectionLimit: parseInt(process.env.DB_CONNECTION_LIMIT) || 100,
  queueLimit: 0,
  // 连接超时设置
  connectTimeout: 10000,
  // 查询超时设置
  timeout: 60000,
  // 启用多语句查询（谨慎使用）
  multipleStatements: false,
  // 时区设置
  timezone: '+08:00',
  // 字符集
  charset: 'utf8mb4',
  // 支持大数字
  supportBigNumbers: true,
  bigNumberStrings: true,
  // 日期字符串化
  dateStrings: ['DATE', 'DATETIME'],
  // MySQL 8.0 兼容性：允许旧的认证方式
  insecureAuth: true
};

// 创建数据库连接池（Promise 版本）
const pool = mysql.createPool(dbConfig);

// 测试数据库连接
const testConnection = async () => {
  try {
    const connection = await pool.getConnection();
    console.log('✓ 数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    console.error('✗ 数据库连接失败:', error.message);
    return false;
  }
};

// 获取连接（Promise 版本）
const getConnection = async () => {
  try {
    return await pool.getConnection();
  } catch (error) {
    console.error('获取数据库连接失败:', error.message);
    throw error;
  }
};

// 执行查询的便捷方法（自动管理连接）
const query = async (sql, params = []) => {
  const connection = await getConnection();
  try {
    const [rows] = await connection.execute(sql, params);
    return rows;
  } finally {
    connection.release();
  }
};

// 执行事务
const transaction = async (callback) => {
  const connection = await getConnection();
  try {
    await connection.beginTransaction();
    const result = await callback(connection);
    await connection.commit();
    return result;
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

// 优雅关闭连接池
const closePool = async () => {
  try {
    await pool.end();
    console.log('✓ 数据库连接池已关闭');
  } catch (error) {
    console.error('✗ 关闭数据库连接池失败:', error.message);
  }
};

// 监听进程退出事件
process.on('SIGINT', async () => {
  await closePool();
  process.exit(0);
});

process.on('SIGTERM', async () => {
  await closePool();
  process.exit(0);
});

module.exports = {
  pool,
  getConnection,
  query,
  transaction,
  testConnection,
  closePool
};